﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SyndicateDAO.DAO;
using SyndicateDAO.DatabaseObject;

namespace SyndicateBusiness.Classes
{
    public class DrawBL
    {
        private DrawDAO DrawDAO = new DrawDAO();
        private PlayerDAO PlayerDAO = new PlayerDAO();
        private UserDAO UserDAO = new UserDAO();
        private LineDAO LineDAO = new LineDAO();
        private CouponDAO CouponDAO = new CouponDAO();
        private ResultDAO ResultDAO = new ResultDAO();

        public IQueryable<draw> GetAllBySyndicateId(int sId)
        {
            return DrawDAO.SelectAllBySyndicateId(sId);
        }

        public IQueryable<draw> GetAllBySyndicateId(DataContext dc, int sId)
        {
            return DrawDAO.SelectAllBySyndicateId(dc,sId);
        }

        public draw GetSingleById(int id)
        {
            return DrawDAO.SelectSingleById(id);
        }
        public draw SelectSingleByDateAndSyndicateId(DateTime date, int sId)
        {
            return DrawDAO.SelectSingleByDateAndSyndicateId(date, sId);
        }
        public bool InsertDraw(draw d)
        {
            return DrawDAO.InsertDraw(d);
        }
        public bool UpdateDraw()
        {
            return DrawDAO.UpdateDraw();
        }
        public bool DeleteDraw(draw d)
        {
            return DrawDAO.DeleteDraw(d);
        }

        #region players
        
        public IQueryable<player> GetPlayers(int dId)
        {
          return  PlayerDAO.SelectAllByDrawId(dId);

        }

        public IQueryable<user> GetAvailableUsers(int dId)
        {
           

            var sId = GetSingleById(dId).syndicate.id;

            return UserDAO.SelectAllBySyndicateId(sId);
                       
        }

        public IQueryable<user> GetUnassignedUsers(int dId)
        {
            var playersIds = GetPlayers(dId).Select(p => p.userId).ToList();

            var allUsers = GetAvailableUsers(dId);

            var unassigned = allUsers.Where(u => !playersIds.Contains(u.id));

            return (IQueryable<user>)unassigned;
        }

        #endregion

        public IQueryable<line> GetLines(int dId)
        {
            return LineDAO.SelectAllByDrawId(dId);
        }

        public IQueryable<coupon> GetCoupons(int dId)
        {
          return CouponDAO.SelectAllByDrawId(dId);
        }

        public result GetResult(int dId)
        {
            return ResultDAO.SelectAllByDrawId(dId).FirstOrDefault();
                        
        }

        public IQueryable<player> GetPaidPlayers(int dId)
        {
            return PlayerDAO.SelectAllByDrawId(dId).Where(p => p.freePlay == false);
        }

        public IQueryable<player> GetFreePlayers(int dId)
        {
            return PlayerDAO.SelectAllByDrawId(dId).Where(p=>p.freePlay == true);
        }
    }
}
